<template>
    <div>
        <page-view>
            <template #option>
                <div class="btn-box">
                    <el-button type="primary" @click="add">新增</el-button>
                    <el-button type="primary" @click="dockBudgetHandle" v-auth="'dock_budget'" :loading="btnLoading">对接预算</el-button>
                </div>
            </template>

            <template #form>
                <SearchForm :data-form="formInline" @on-search="onSearch" @onReset="onSearch">
                    <el-form-item prop="years" label-width="60px">
                        <el-input placeholder="请输入年度" v-model="formInline.years" clearable></el-input>
                    </el-form-item>
                    <el-form-item prop="budgetName">
                        <el-input v-model="formInline.budgetName" placeholder="请输入名称" clearable />
                    </el-form-item>
                    <el-form-item prop="budgetType">
                        <el-select v-model="formInline.budgetType" clearable placeholder="请选择预算类型">
                            <el-option v-for="item in BUDGET_TYPE_LIST" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="orgCode">
                        <companySearch :back-value="formInline.orgCode" class="w100p" @select="selectCompany">
                        </companySearch>
                    </el-form-item>
                    <el-form-item prop="budgetStatus">
                        <el-select v-model="formInline.budgetStatus" clearable placeholder="请选择状态">
                            <el-option v-for="item in STATUS_LIST" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </SearchForm>
            </template>
            <template #table="tableScope">
                <PubilcTable :table-data="tableData" :isSlot="false" :list-config="TEMPLATE_CONFIG"
                    :page-data="pageData" @on-action="onAction" :translateTextDeal="translateTextDeal"
                    :tableHeight="tableScope.tableHeight" :actionLimitName="actionLimitName"
                    :actionLimit="actionLimit" :loading="tableLoading" />
            </template>
        </page-view>
        <addAndEdit :dialogVisible="dialogVisible" v-if="dialogVisible" :type="type" @handleClose="handleClose"
            @on-update="onSearch"></addAndEdit>
        <historyVerson :dialogVisible="dialogVisibleHistory" v-if="dialogVisibleHistory" @handleClose="handleClose"
            :budgetNo="listId" :info="rowInfo" @update="onSearch"></historyVerson>
        <submitAuditDialog :dialogVisible="dialogVisibleAudit" v-if="dialogVisibleAudit" @handleClose="handleClose"
            @on-update="onSearch" :id="pageId"></submitAuditDialog>
    </div>
</template>
<script  setup name="Standard">
import { reactive } from 'vue'
import { TEMPLATE_CONFIG, STATUS_LIST, BUDGET_TYPE_LIST, TIME_WEEK_LIST, WEEK_LIST, ROLL_ENABLED_LIST } from './Common/config'
import { statusText } from '@/util/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import addAndEdit from './Common/addAndEdit.vue';
import historyVerson from './Common/historyVerson.vue'
import submitAuditDialog from './Common/submitAuditDialog.vue'
import dayjs from 'dayjs'
import api from '@/api'



const router = useRouter()

const formInline = ref({
    years: '',
    budgetType: '',
    budgetName: '',
    budgetStatus: '',
    orgCode: ''
})
const pageData = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const tableData = ref([])


const type = ref('add')

const dialogVisible = ref(false)

const dialogVisibleHistory = ref(false)

const dialogVisibleAudit = ref(false)

const listId = ref('')

const pageId = ref('')

const btnLoading = ref(false)

const rowInfo = ref({})

const tableLoading = ref(false)

// 预算编制 新增预算科目 如果 预算类型为费用预算 则预算科目顶级为成本中心 如果是项目预算顶级为 项目名称
onMounted(() => {
    getList()

})
const onSearch = () => {
    pageData.value.pageNum = 1
    getList()
}

// 获取列表数据
const getList = () => {
    const parms = {
        ...pageData.value,
        ...formInline.value
    }
    tableLoading.value = true
    api.budgetManger.budgetMangerList(parms).then(res => {
        const { list, total } = res
        list.forEach(item => {
            item['startTime'] = dayjs(item['startTime']).format('YYYY-MM-DD')
            item['endTime'] = dayjs(item['endTime']).format('YYYY-MM-DD')
        })
        pageData.value.total = total
        tableData.value = list
         tableLoading.value = false

    })

}


const editRow = (row) => {
    router.push({
        name: 'staffingEdit',
        query: { id: row.id, type: 'add', centerName: row.centerName }
    })

}

const lookDetail = (row) => {
    router.push({
        name: 'staffingEdit',
        query: { id: row.id, type: 'look', centerName: row.centerName }
    })
}

const lookHistory = (row) => {
    dialogVisibleHistory.value = true
    listId.value = row.budgetNo
    rowInfo.value = row

}

const delRow = (row) => {
    ElMessageBox.confirm(
        '您确定要进行删除操作吗?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            api.budgetManger.budgetMangerDel({ id: row.id }).then(res => {
                onSearch()
                ElMessage.success('操作成功')
            })
        })

}

const updateStatus = (row) => {
    let text = row.budgetStatus == 'ENABLE' ? '停用' : '启用'
    ElMessageBox.confirm(
        `您确定要进行${text}操作吗?`,
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            api.budgetConfig.budgetUpdateStatus({ state: row.budgetStatus == 'ENABLE' ? "disable" : "enable", id: row.id }).then(res => {
                onSearch()
                ElMessage.success('操作成功')
            })
        })
}

const selectCompany = (obj) => {
    formInline.value.orgCode = obj.orgCode
}

const submitAuditHandl = (row) => {
    dialogVisibleAudit.value = true
    pageId.value = row.id

}

// 列表操作 分页
const onAction = ([item, row]) => {
    console.log(7777)
    const obj = {
        'edit': editRow,
        'del': delRow,
        'change': lookHistory,
        'satate': updateStatus,
        'submit': submitAuditHandl,
        'look': lookDetail,
        'pageNum': getList,
        'pageSize': onSearch
    }
    if (typeof item === 'string') {
        pageData.value[item] = row
        obj[item]()
    } else {
        obj[item.alias](row)
    }
}
// 显示新增弹框
const add = () => {
    dialogVisible.value = true
    type.value = 'add'

}
// 操作按钮名称调整
const actionLimitName = ([row, filed]) => {
    const info = { ...filed }
    if (filed.alias === 'satate') {
        filed['label'] = row.budgetStatus == 'ENABLE' ? '停用' : '启用'
    }

    return filed.label
}
const translateTextDeal = (item, val, row) => {
    let text = ''
    if (item.alias == 'budgetRollEnabled') text = statusText(ROLL_ENABLED_LIST, val)
    if (item.alias == 'budgetType') text = statusText(BUDGET_TYPE_LIST, val)
    if (item.alias == 'budgetStatus') text = statusText(STATUS_LIST, val)
    if (item.alias == 'cycleType') {
        const cycleTypeList = [...WEEK_LIST, ...TIME_WEEK_LIST]
        if (val == 'NO_CYCLE') {
            text = `${row.startTime} 至 ${row.endTime}`
        } else {
            text = statusText(cycleTypeList, val)
        }

    }
    return text

}
const actionLimit = ([item, row]) => {
    let flag = false
    // 不能使用的按钮放到数组中
    if (item.budgetStatus == 'DRAFT') {
        // 草稿
        flag = ['satate', 'change'].includes(row.alias)
    } else if (item.budgetStatus == 'CHANGING') {
        //变更中
        flag = ['del', 'satate'].includes(row.alias)
    } else if (['ENABLE'].includes(item.budgetStatus)) {
        // 启用
        flag = ['del', 'submit'].includes(row.alias)
    }
    else if (['DISABLE'].includes(item.budgetStatus)) {
        // 停用
        flag = ['del', 'submit', 'edit'].includes(row.alias)
    }
    else if (['AUDITING'].includes(item.budgetStatus)) {
        // 审批中
        flag = ['satate', 'del', 'AUDITING', 'ENABLE', 'submit', 'change', 'edit'].includes(row.alias)
    }
    return flag
}

const handleClose = () => {
    dialogVisible.value = false
    dialogVisibleHistory.value = false
    dialogVisibleAudit.value = false
}

// 对接预算
const dockBudgetHandle = () => {
    const yearRegex = /^\d{4}$/
    const { years, orgCode, budgetType } = formInline.value
    if (!yearRegex.test(years)) return ElMessage.error('请输入正确的年度')
    ElMessageBox.confirm(
        '是否确定对接预算系统的全年预算?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const data = {
                year: years
            }
            btnLoading.value = true
            ElMessage.warning('等待时间较长，请半小时候查看结果')
            api.budgetConfig.budgetDocking(data).then(res => {
                onSearch()
                ElMessage.success('操作成功')
                btnLoading.value = false
            }).catch(err => {
                btnLoading.value = false
            })
        })

}
// onActivated(() => {
//     onSearch()

// })
</script>
